<script setup lang="tsx">
import { rules } from '@/pages/serve/project/constants'
import { ref, watch, computed } from 'vue'
import { MessagePlugin } from 'tdesign-vue-next'
//1.DialogForm组件对外的props
const props = defineProps({
  dialogVisibleProp: {
    type: Boolean,
    default: false,
    required: true
  },
  dialogTitleProp: {
    type: String,
    default: '新增',
    required: true
  },
  dialogFormDataProp: {
    type: Object,
    default: () => {},
    required: true
  }
})
const dialogFormData = ref<DialogFormData>({
  name: '',
  price: 0.0,
  unit: '',
  orderNo: 1,
  status: 1,
  image: '',
  nursingRequirement: '',
  id: undefined
})
interface DialogFormData {
  name: string
  price: number
  unit: string
  orderNo: number
  status: number
  image: string
  nursingRequirement: string
  id: any
}

//监听dialogFormDataProp转变成dialogFormData
watch(
  //对某一个对象进行检测
  () => props.dialogFormDataProp,
  //如果检测到值变化，就执行函数
  (newValue) => {
    dialogFormData.value = newValue as DialogFormData
    imageFiles.value = [{ url: dialogFormData.value.image }]
  },
  {
    //如果监控的对象比较复杂,内部的属性发生了变化,则可以调用上面回调函数
    deep: true
  }
)
//监听dialogVisibleProp转变成dialogVisible
const dialogVisible = ref(false)
watch(
  () => props.dialogVisibleProp,
  (newValue) => {
    dialogVisible.value = newValue
  }
)

//2.DialogForm组件对外的events
const emits = defineEmits(['onDialogFormResetEmit', 'onDialogFormSubmitEmit'])

const onDialogFormReset = () => {
  dialogFormRef.value.reset()
  imageFiles.value = []
  dialogFormData.value.image = ''
  //父组件事件会被调用,设置弹层隐藏
  emits('onDialogFormResetEmit')
  MessagePlugin.success('重置成功')
}
const onDialogFormSubmit = ({ validateResult, firstError }) => {
  if (validateResult === true) {
    emits('onDialogFormSubmitEmit', dialogFormData.value)
    dialogFormRef.value.reset()
    imageFiles.value = []
    dialogFormData.value.image = ''
  } else {
    console.log('Validate Errors:', firstError, validateResult)
    MessagePlugin.warning(firstError)
  }
}
//3.DialogForm组件对内的属性
const dialogFormRef = ref(null)
const imageFiles = ref([])
const uploadRef = ref(null)
const imageViewerProps = ref({
  closeOnEscKeydown: false
})
const sizeLimit = ref({
  size: 500,
  type: 'MB'
})
//statusString<===类型数据互转===>dialogFormData.value.status
const statusString = computed({
  get() {
    return dialogFormData.value.status == 1 ? '1' : '0'
  },
  set(value) {
    dialogFormData.value.status = value === '1' ? 1 : 0
  }
})
//4.DialogForm组件对内的事件
const onUploadSuccess = (context) => {
  //图片回显
  const uploadImageUrl = context.response.data
  imageFiles.value[0].url = uploadImageUrl
  dialogFormData.value.image = uploadImageUrl
}
const handleUploadFail = ({ file }) => {
  MessagePlugin.error(`文件${file.name}上传失败`)
}
</script>
<template>
  <t-dialog
    v-model:visible="dialogVisible"
    attach="body"
    :header="dialogTitleProp + '护理项目'"
    width="540px"
    destroy-on-close
    :footer="false"
    @close="onDialogFormReset"
  >
    <template #body>
      <div class="form-container">
        <t-form
          ref="dialogFormRef"
          :data="dialogFormData"
          :rules="rules"
          requiredMark
          colon
          @reset="onDialogFormReset"
          @submit="onDialogFormSubmit"
        >
          <t-form-item label="护理项目名称" name="name">
            <t-input
              v-model="dialogFormData.name"
              placeholder="请输入"
              :maxlength="10"
              show-limit-number
              clearable
            ></t-input>
          </t-form-item>

          <t-form-item label="价格" name="price">
            <t-input-number
              v-model="dialogFormData.price"
              :decimal-places="2"
            />
          </t-form-item>

          <t-form-item label="单位" name="unit">
            <t-input
              v-model="dialogFormData.unit"
              placeholder="请输入"
              :maxlength="5"
              show-limit-number
              clearable
            ></t-input>
          </t-form-item>

          <t-form-item label="排序" name="orderNo">
            <t-input-number v-model="dialogFormData.orderNo" />
          </t-form-item>

          <t-form-item label="状态" name="status">
            <t-radio-group v-model="statusString">
              <t-radio value="1">启用</t-radio>
              <t-radio value="0">禁用</t-radio>
            </t-radio-group>
          </t-form-item>

          <t-form-item label="护理图片" name="image">
            <t-upload
              ref="uploadRef"
              v-model="imageFiles"
              :image-viewer-props="imageViewerProps"
              :size-limit="sizeLimit"
              action="/api/common/upload"
              theme="image"
              tips="图片大小不超过2M，仅支持上传PNG,JPG,JPEG类型图片"
              accept="image/*"
              :disabled="false"
              :auto-upload="true"
              :show-image-file-name="true"
              :upload-all-files-in-one-request="false"
              :locale="{
                triggerUploadText: {
                  image: '请选择图片'
                }
              }"
              @fail="handleUploadFail"
              :onSuccess="onUploadSuccess"
            >
            </t-upload>
          </t-form-item>

          <t-form-item label="护理项目描述" name="nursingRequirement">
            <t-input
              v-model="dialogFormData.nursingRequirement"
              placeholder="请输入"
              :maxlength="50"
              show-limit-number
              clearable
            ></t-input>
          </t-form-item>

          <t-form-item :requiredMark="false">
            <t-space size="small">
              <t-button
                theme="default"
                variant="base"
                type="reset"
                @click="onDialogFormReset"
                >取消</t-button
              >
              <t-button
                theme="primary"
                type="submit"
                @click="onDialogFormSubmit"
                >提交</t-button
              >
            </t-space>
          </t-form-item>
        </t-form>
      </div>
    </template>
  </t-dialog>
</template>
<style scoped>
.form-container {
  max-height: 400px;
  /* 根据需要调整高度 */
  overflow-y: auto;
}
</style>
